class SessionController < Devise::SessionsController
  prepend_before_filter :require_no_authentication, :only => :new
  protect_from_forgery :except => [:create, :new]

  def create
    resource = warden.authenticate(:scope => resource_name, :recall => :failure)
    if resource
      return sign_in_and_redirect(resource_name, resource)
    else
      return render :json => {:errorCode => 1501, :errorDescription => "User not login"}
    end
  end

  def success(resource)
    if resource.nil?
      {
          :success => true,
          :redirect => stored_location_for(scope) || after_sign_in_path_for(resource)
      }
    else
      {
          success: true,
          email: resource.email,
          default_currency: resource.default_currency_code,
          default_wallet: "@#{resource.default_wallet.name}"
      }
    end
  end

  def sign_in_and_redirect(resource_or_scope, resource=nil)
    scope = Devise::Mapping.find_scope!(resource_or_scope)
    resource ||= resource_or_scope
    sign_in(scope, resource) unless warden.user(scope) == resource
    return render :json => success(resource)
  end

  def failure
    return render:json => {:success => false, :errors => ["Login failed."]}
  end

=begin
  # WITH JSON RESPONSE
  def sign_in_and_redirect(resource_or_scope, resource=nil, skip=false)
    scope      = Devise::Mapping.find_scope!(resource_or_scope)
    resource ||= resource_or_scope
    sign_in(scope, resource) unless skip
    respond_to do |format|
      format.html {redirect_to stored_location_for(scope) || after_sign_in_path_for(resource) }
      format.json { render :json => { :success => true, :session_id => request.session_options[:id], :current_user => current_user} }
    end
  end

  # POST /resource/sign_in
  def create
    resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
    set_flash_message :notice, :signed_in


    respond_to do |format|
      format.html {sign_in_and_redirect(resource_name, resource)}

      token = {Rack::Utils.escape_html(request_forgery_protection_token) => Rack::Utils.escape_html(form_authenticity_token)}
      format.xml  { render :xml => token }
      format.json  { render :json => token.as_json }
    end
  end
=end
end
